const Joi = require('@hapi/joi');
const dateFormat = require('dateformat');
const CryptoJS = require("crypto-js");

//  抽奖主要逻辑
exports.drawPrize = async (context) => {
  const { cloud, mixNick } = context;

  //  查询当前用户是否抽奖
  let data = await context.cloud.dataspace.executeSql('SELECT count(1) as total FROM lottery_user WHERE mixnick = ?', [mixNick]);
  console.log("###########  drawPrize--data :::", data);
  if(data && data[0].total > 0){
    return {
      success: false,
      msg: "已经抽过奖了",
      code: 10001
    };
  }

  //  获取奖池数组
  let prizeArr = await context.cloud.dataspace.executeSql('SELECT * FROM lottery_item', []);
  console.log("###########  drawPrize--prizeArr :::", prizeArr);
  //  进行抽奖
  let awardRes = await drawFun(prizeArr);
  if(awardRes && awardRes.isAward){
    //  当前奖品是否每日限量发放
    if(awardRes.info.is_every){
      //  发奖(限制每日发放次数)
      return await changeAwardEveryNum(awardRes, context);
    }else{
      // 发奖(不用限制每日发放)
      return await changeAwardNum(awardRes, context);
    }
  }else{
    //  存储用户抽奖记录
    await context.cloud.dataspace.executeSql(`INSERT INTO lottery_user ( mixnick, award_id, is_award, gmt_create, gmt_modified ) 
  VALUES ( ?, ?, ?, now(), now());`, [mixNick, 0, 0]);
    return {
      success: true,
      isAward: false,
      msg: "未中奖",
    };
  }
}

//  抽奖逻辑
async function drawFun(prizeArr){
  return new Promise((resolve, reject) => {
    //初始化随机数
    let random = (Math.random()*10000).toFixed(5);
    //初始化奖品概率
    let shopRates = 0;
    //初始阶段
    let startRate = 0;
    //初始化中奖id
    let shopId = 0;
    //奖池划分，并且抽出奖品
    for(let i = 0; i < prizeArr.length; i++){
      //查询概率配置
      if(i == 0){
        shopRates += prizeArr[i].award_rate;
      }else{
        startRate = shopRates;
        shopRates += prizeArr[i].award_rate;
      }
      //每个产品的概率
      console.log('这是每个产品的概率',startRate,shopRates,random)
      if(random > startRate && random <= shopRates){
        shopId = prizeArr[i];
        break;
      }
    }
    if(shopId == 0){
      resolve({info:shopId, isAward: false});
    }else{
      resolve({info:shopId, isAward: true});
    }
  })
}

//  发奖，减小奖品数量
async function changeAwardEveryNum(awardRes, context){
  const { cloud, mixNick } = context;
  let giveAward = await context.cloud.dataspace.executeSql(`UPDATE lottery_item SET 
			every_num = every_num - 1,
			award_total = award_total - 1,
			give_num = give_num + 1,
			gmt_modified = now()
			WHERE id = ? and award_total > 0 and every_num > 0;`, [awardRes.info.id]);
  console.log("###########  drawPrize--changeAwardEveryNum--giveAward :::", giveAward);
  if(giveAward && giveAward.affectedRows){
    //  存储用户抽奖记录
    let drawRes = await context.cloud.dataspace.executeSql(`INSERT INTO lottery_user ( mixnick, award_id, is_award, gmt_create, gmt_modified ) 
    VALUES ( ?, ?, ?, now(), now());`, [mixNick, awardRes.info.id, 1]);
    console.log("###########  drawPrize--changeAwardEveryNum--drawRes :::", drawRes);
    if(drawRes && drawRes.insertId){
      return {
        success: true,
        isAward: true,
        msg: "中奖",
        code: 0,
        id: awardRes.info.id,
      };
    }else{
      return {
        success: true,
        isAward: false,
        msg: "未中奖",
        code: 10004
      };
    }
  }else{
    //  存储用户抽奖记录
    await context.cloud.dataspace.executeSql(`INSERT INTO lottery_user ( mixnick, award_id, is_award, gmt_create, gmt_modified ) 
    VALUES ( ?, ?, ?, now(), now());`, [mixNick, awardRes.info.id, 0]);
    return {
      success: true,
      isAward: false,
      msg: "未中奖",
      code: 10003
    };
  }
}

//  发奖(不用限制每日发放)
async function changeAwardNum(awardRes, context){
  const { cloud, mixNick } = context;
  //  奖品数量减小
  let giveAward = await context.cloud.dataspace.executeSql(`UPDATE lottery_item SET
			award_total = award_total -1,
			give_num = give_num + 1, 
			gmt_modified = now()
			WHERE id = ? and award_total > 0`, [ awardRes.info.id ]);
  console.log("###########  drawPrize--changeAwardNum--giveAward :::", giveAward);
  if(giveAward && giveAward.affectedRows){
    //  存储用户抽奖记录
    let drawRes = await context.cloud.dataspace.executeSql(`INSERT INTO lottery_user ( mixnick, award_id, is_award, gmt_create, gmt_modified ) 
    VALUES ( ?, ?, ?, now(), now());`, [mixNick, awardRes.info.id, 1]);
    console.log("###########  drawPrize--changeAwardNum--drawRes :::", drawRes);
    if(drawRes && drawRes.insertId){
      return {
        success: true,
        isAward: true,
        msg: "中奖",
        code: 0,
        id: awardRes.info.id,
      };
    }else{
      return {
        success: true,
        isAward: false,
        msg: "未中奖",
        code: 10002
      };
    }
  }else{
    //  存储用户抽奖记录
    await context.cloud.dataspace.executeSql(`INSERT INTO lottery_user ( mixnick, award_id, is_award, gmt_create, gmt_modified ) 
    VALUES ( ?, ?, ?, now(), now());`, [mixNick, awardRes.info.id, 0]);
    return {
      success: true,
      isAward: false,
      msg: "未中奖",
      code: 10001
    };
  }
}

/*
  *  存储用户收货地址
  *
  *  mixnick  string  混淆昵称
  *  name  string  名字
  *  phone  string  电话
  *  address  string  地址
  *  backup_info  string  备用字段
  *  backup_info2  string  备用字段2
  *  backup_info3  string  备用字段3
  *  backup_info4  string  备用字段4
  *
  * */
exports.saveUserAddress = async (context) => {
  const { cloud, mixNick, data } = context;
  const schema = Joi.object({
    name: Joi.string(),
    phone: Joi.string(),
    address: Joi.string(),
    backup_info: Joi.string(),
    backup_info2: Joi.string(),
    backup_info3: Joi.string(),
    backup_info4: Joi.string()
  }).or('name', 'phone', 'address', 'backup_info', 'backup_info2', 'backup_info3', 'backup_info4');;
  // 参数校验
  let validate = schema.validate(context.data);
  if(validate.error){
    return {success: false, code: 10422, msg: "参数错误", data: validate};
  }
  // let num = 0;
  // for(let key in data){
  //   if(!data[key]) num ++;
  // }
  // if(num == 0){
  //   return {
  //     success: false,
  //     msg: "参数缺失",
  //     code: 10004
  //   };
  // }
  //  判断当前用户是否中奖
  let isRealAward = await context.cloud.dataspace.executeSql(`SELECT 
			u.id,
			u.mixnick,
			u.is_award,
			u.award_info_id,
			i.id as award_id, 
			i.award_name
		FROM lottery_user u, 
			lottery_item i 
		WHERE
			u.mixnick = ?
			AND u.award_id = i.id
			AND u.is_award = 1;`, [mixNick]);
  console.log("###########  drawPrize--saveUserAddress--isRealAward :::", isRealAward);
  if(isRealAward && isRealAward.length){
    data.name = data.name || "";
    data.phone = data.phone || "";
    data.address = data.address || "";
    data.backup_info = data.backup_info || "";
    data.backup_info2 = data.backup_info2 || "";
    data.backup_info3 = data.backup_info3 || "";
    data.backup_info4 = data.backup_info4 || "";
    if(isRealAward[0].award_info_id != null){
      //  收货地址不允许更新
      // return {
      //   success: false,
      //   msg: "你的地址信息已经填写了哦！",
      //   code: 10005
      // };
      //  更新用户中奖地址信息
      let addresRes = await context.cloud.dataspace.executeSql(`UPDATE lottery_address SET
        name = '${data.name}',
        phone = '${data.phone}',
        address = '${data.address}',
        backup_info = '${data.backup_info}',
        backup_info2 = '${data.backup_info2}',
        backup_info3 = '${data.backup_info3}',
        backup_info4 = '${data.backup_info4}',
        gmt_modified = now()
        WHERE id = ${isRealAward[0].award_info_id};`, []);
      console.log("###########  drawPrize--saveUserAddress--addresRes :::", addresRes);
      if(addresRes && addresRes.affectedRows){
        return {
          success: true,
          msg: "更新地址信息成功",
          code: 0
        };
      }else{
        return {
          success: false,
          msg: "更新地址信息失败",
          code: 10005
        };
      }
    }else{
      //  新增用户中奖地址信息
      let address = await context.cloud.dataspace.executeSql(`INSERT INTO lottery_address ( name, phone, address, backup_info, backup_info2, backup_info3, backup_info4, gmt_create, gmt_modified ) 
    VALUES ( '${data.name}', '${data.phone}', '${data.address}', '${data.backup_info}', '${data.backup_info2}', '${data.backup_info3}', '${data.backup_info4}', now(), now());`, []);
      console.log("###########  drawPrize--saveUserAddress--address :::", address);
      if(address && address.insertId){
        //  更新用户中奖记录表
        let updateRes = await context.cloud.dataspace.executeSql(`UPDATE lottery_user SET
          award_info_id = ?,
          gmt_modified = now()
          WHERE mixnick = ? and award_id != 0 and is_award = 1;`, [address.insertId, mixNick]);
        console.log("###########  drawPrize--saveUserAddress--updateRes :::", updateRes);
        if(updateRes && updateRes.affectedRows){
          return {
            success: true,
            msg: "存储地址信息成功",
            code: 0
          };
        }else{
          return {
            success: false,
            msg: "存储地址信息失败",
            code: 10003
          };
        }
      }else{
        return {
          success: false,
          msg: "存储地址信息失败",
          code: 10002
        };
      }
    }
  }else{
    return {
      success: false,
      msg: "你并没有中奖哦！",
      code: 10001
    };
  }
}

//  奖品数据插入
exports.initPrizeData = async (context) => {
  const { cloud, mixNick, data } = context;
  let res = await context.cloud.dataspace.executeSql(`INSERT INTO lottery_item ( award_name, award_rank, award_total, award_rate, give_num, every_num, is_every, gmt_create, gmt_modified ) 
    VALUES ( '${data.award_name}', '${data.award_rank}', '${data.award_total}', '${data.award_rate}', '${data.give_num}', '${data.every_num}', '${data.is_every}', now(), now())`, []);
  return res;
}

//  根据id删除中奖纪录
exports.delPrizeData = async (context) => {
  const { cloud, mixNick, data } = context;
  let res = await context.cloud.dataspace.executeSql('DELETE FROM lottery_user WHERE id = ?', [data.id]);
  return res;
}

//  根据id删除奖品地址信息
exports.delAddressData = async (context) => {
  const { cloud, mixNick, data } = context;
  let res = await context.cloud.dataspace.executeSql('DELETE FROM lottery_address WHERE id = ?', [data.id]);
  return res;
}